import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:sciolto/POJO/SongList.dart';
import 'package:sciolto/UI/songListPage.dart';
import 'package:sciolto/api/Common_api.dart';
import 'package:sciolto/api/music.dart';
import 'package:sciolto/util/setting.dart';
import 'package:sciolto/widget/custom_route.dart';
import 'package:sciolto/widget/custom_widget.dart';

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {

  /// 整个Widget的尺寸类
  Size _size;

  /// 构建界面的x,y方向的单位长度
  double _x, _y;

  /// 应用主界面的标题
  String title = 'Sciolto';

  /// 主界面通过异步操作获取的歌单列表
  List<SongList> _listOfSongList;

  /// 将歌单列表按照点击量降序排序后形成的列表
  List<SongList> _orderedList;

  /// 是否已经异步获取到歌单信息
  /// [_hasLoaded] :
  ///   false : 显示一个加载组件[CircularProgressIndicator]在界面中心
  ///   true  : 显示歌单
  bool _hasLoaded;


  /// ------------------ 方法 -----------------------


  /// 第一次初始化界面时调用
  ///
  /// 首先先设置当前并没有获取到歌单信息
  /// 当[_getListOfSonglist]返回数值后，初始化[_listOfSongList]，并标记以获得到歌单信息
  /// details:
  ///
  /// * [_hasLoaded]
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _hasLoaded = false;
    _getListOfSonglist().then((value) {
      _listOfSongList = value;
      _hasLoaded = true;
      setState(() {});
    });
  }

  /// 每次更新状态时调用
  ///
  /// 在这个阶段已经初始化了context，可以获取到根组件的尺寸
  /// details:
  ///
  /// * [CommonApi.initParameter]
  /// * [Size]
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _size ??= CommonApi.initParameter(context);
    _x ??= _size.width / 420;
    _y ??= _size.height / 800;
  }

  /// 当点击主界面右上角加号按钮时调用
  ///
  /// 该方法会弹出一个[CustomWidget.showCustomDialog]来给出进一步操作
  /// 当操作结束后，即弹出界面被pop后，通过[_getListOfSonglist]来更新歌单列表信息
  /// 并且更新界面
  /// details:
  ///
  /// * [CustomWidget.showCreateSonglistView]
  /// * [_getListOfSonglist]
  void _onPressAddButton() {
    CustomWidget.showCreateSonglistView(context, _size, _x, _y).then((value) {
      _hasLoaded = false;
      _getListOfSonglist().then((value) {
        _listOfSongList = value;
        _hasLoaded = true;
        setState(() {});
      });
    });
  }

  /// 获取歌单列表的操作
  /// details:
  ///
  /// * [SongsInfo]
  Future<List<SongList>> _getListOfSonglist() => SongsInfo().getSongLists();

  /// 初始化或更新有序列表
  /// 会通过传入的歌单列表，根据歌单的点击量来返回一个降序的列表
  /// details:
  ///
  /// * [SongList]
  List<SongList> orderingList(List<SongList> list) {
    _orderedList = list.toList()
      ..removeWhere((element) => element.listName == "全部歌曲");
    for (int i = _orderedList.length - 1; i >= 0; i--)
      for (int j = 0; j < i; j++) {
        if (_orderedList[j].hits < _orderedList[j + 1].hits) {
          SongList temp = _orderedList[j];
          _orderedList[j] = _orderedList[j+1];
          _orderedList[j+1] = temp;
        }
      }
    return _orderedList;
  }


  /// -------------  组件构造器 ----------------


  /// 该方法会返回当成功获取歌单列表后的主界面
  Widget _songListPerformWidget(constraints) {
    return SizedBox(
      width: constraints.maxWidth,
      height: constraints.maxHeight,
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Container(
          width: _size.width,
          height: constraints.maxHeight + 1.0,
          padding: EdgeInsets.symmetric(horizontal: 20 * _x),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                height: 5 * _y,
              ),
              Container(
                width: _size.width,
                height: 40 * _y,
                alignment: Alignment.centerRight,
                child: IconButton(
                  padding: EdgeInsets.all(0),
                  icon: Icon(
                    Icons.add,
                    color: Colors.blueGrey[200],
                  ),
                  iconSize: 40 * _y,
                  onPressed: _onPressAddButton,
                ),
              ),
              Container(
                height: 5 * _y,
              ),
              songListSet("| 我的歌单", _listOfSongList, _size, context),
              songListSet(
                  "| 最近常听", orderingList(_listOfSongList), _size, context),
              Container(
                height: 1.0,
              )
            ],
          ),
        ),
      ),
    );
  }

  /// 该方法会返回当获取歌单列表出现错误时的主界面
  Widget _errorPerformWidget() {
    return RefreshIndicator(
      color: Colors.white,
      backgroundColor: Colors.cyanAccent,
      onRefresh: () {
        return Future.delayed(Duration(seconds: 1), () {
          setState(() {});
        });
      },
      child: Center(
        child: Text(
          "出现了意料之外的错误QXQ",
          style: TextStyle(fontSize: 20 * _y, color: Colors.cyanAccent),
        ),
      ),
    );
  }

  /// 显示歌单的组件构造器
  Widget songListSet(String listName, List<SongList> listOfSonglist, Size _size,
      BuildContext context) {
    double _x = _size.width / 420, _y = _size.height / 800;
    return Expanded(
      flex: 1,
      child: Container(
        width: _size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: _size.width,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 20 * _x),
              child: Text(
                listName,
                style: TextStyle(
                    fontSize: 15 * _x,
                    color: Colors.blueGrey,
                    wordSpacing: 1,
                    fontWeight: FontWeight.w900),
              ),
            ),
            Container(
              height: 5 * _y,
            ),
            Expanded(
              flex: 1,
              child: LayoutBuilder(
                builder: (context, constraints) {
                  return Container(
                    child: ListView.separated(
                        physics: BouncingScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (BuildContext context, index) {
                          SongList currentSonglist = listOfSonglist[index];
                          return Padding(
                            padding: EdgeInsets.all(20 * _x),
                            child: Ink(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(10 * _y)),
                              child: InkWell(
                                borderRadius: BorderRadius.circular(10 * _y),
                                child: MaterialButton(
                                  onPressed: () {
                                    SongsInfo()
                                        .clickSonglist(listOfSonglist[index]);
                                    Navigator.of(context)
                                        .push(CustomRoute(
                                            SongListPage(listOfSonglist[index]),
                                            CustomRoute.BOTTOM_TO_TOP,
                                            400))
                                        .then((value) {
                                      _getListOfSonglist().then((value) {
                                        _listOfSongList = value;
                                        setState(() {});
                                      });
                                    });
                                  },
                                  onLongPress: () {
                                    CustomWidget.showAlertDialog(
                                        context: context,
                                        size: _size,
                                        x: _x,
                                        y: _y,
                                        title: "提醒",
                                        content: "确定要删除该歌单吗？",
                                        onPressConfirm: () {
                                          SongsInfo()
                                              .deleteSonglist(
                                                  listOfSonglist[index])
                                              .then((value) {
                                            if (value ==
                                                CreateSonglistState.success) {
                                              CustomWidget.showToast("删除成功");
                                              Navigator.of(context).pop();
                                            }else if(value ==
                                                CreateSonglistState.duplication){
                                                CustomWidget.showToast("不可以删除该歌单");
                                                Navigator.of(context).pop();
                                            }else {
                                              CustomWidget.showToast(
                                                  "出现意料之外的错误");
                                            }
                                          });
                                        }).then((value) {
                                      _getListOfSonglist().then((value) {
                                        _listOfSongList = value;
                                        setState(() {});
                                      });
                                    });
                                  },
                                  padding: EdgeInsets.all(0),
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.circular(10 * _y)),
                                  elevation: 8,
                                  highlightElevation: 2,
                                  minWidth: 140 * _x,
                                  height: constraints.maxHeight,
                                  color: Setting.songListButtonFrontColor,
                                  child: Container(
                                    width: 140 * _x,
                                    decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.circular(10 * _y),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Expanded(
                                            flex: 5,
                                            child: Container(
                                              width: 180 * _x,
                                              // TODO: 需更新为具体图片
                                              child: ClipRRect(
                                                borderRadius: BorderRadius.only(
                                                    topLeft: Radius.circular(
                                                        10 * _y),
                                                    topRight: Radius.circular(
                                                        10 * _y)),
                                                child: Image(
                                                  alignment:
                                                      Alignment.topCenter,
                                                  fit: BoxFit.cover,
                                                  image: AssetImage(
                                                      currentSonglist
                                                          .imagePath),
                                                ),
                                              ),
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.only(
                                                    topLeft: Radius.circular(
                                                        10 * _y),
                                                    topRight: Radius.circular(
                                                        10 * _y)),
                                              ),
                                            )),
                                        Expanded(
                                            flex: 2,
                                            child: Container(
                                              width: 180 * _x,
                                              padding: EdgeInsets.fromLTRB(
                                                  10 * _x, 10 * _y, 10 * _x, 0),
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.only(
                                                    bottomLeft: Radius.circular(
                                                        10 * _y),
                                                    bottomRight:
                                                        Radius.circular(
                                                            10 * _y)),
                                              ),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Expanded(
                                                      flex: 2,
                                                      child: Padding(
                                                        padding: EdgeInsets
                                                            .symmetric(
                                                                horizontal:
                                                                    5 * _x),
                                                        child: Text(
                                                          currentSonglist
                                                              .listName,
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .cyan[300]),
                                                          overflow: TextOverflow
                                                              .ellipsis,
                                                          maxLines: 1,
                                                        ),
                                                      )),
                                                  Expanded(
                                                      flex: 2,
                                                      child: Container(
                                                        child: Row(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .center,
                                                          children: [
                                                            Image(
                                                                image: AssetImage(
                                                                    "images/arrow_right_filling.png")),
                                                            Container(
                                                              width: 5 * _x,
                                                            ),
                                                            Text(
                                                              "${currentSonglist.hits} ${currentSonglist.hits < 1 ? "click" : "clicks"}",
                                                              style: TextStyle(
                                                                  color: Colors
                                                                          .grey[
                                                                      300]),
                                                            )
                                                          ],
                                                        ),
                                                        padding:
                                                            EdgeInsets.only(
                                                                bottom: 5 * _y),
                                                      )),
                                                ],
                                              ),
                                            ))
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context, index) {
                          return Container(
                            width: 20 * _x,
                          );
                        },
                        itemCount: listOfSonglist.length),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    return SizedBox(
      width: _size.width,
      height: _size.height - 140 * _y,
      child: SingleChildScrollView(
        child: SizedBox(
            width: _size.width,
            height: _size.height - 140 * _y,
            child: Scaffold(
              body: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: _size.width,
                    height: 70 * _y,
                    decoration: BoxDecoration(
                      color: Setting.themeColor,
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      title,
                      style:
                          TextStyle(fontSize: 20 * _x, color: Colors.black45),
                    ),
                  ),
                  Expanded(child: LayoutBuilder(
                    builder: (context, constraints) {
                      try {
                        if (_hasLoaded) {
                          return _songListPerformWidget(constraints);
                        } else {
                          return Center(
                            child: CircularProgressIndicator(
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.blueGrey)
                            ),
                          );
                        }
                      } catch (e) {
                        return _errorPerformWidget();
                      }
                    },
                  ))
                ],
              ),
            )),
      ),
    );
  }
}
